package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.constant.UserAuthLogConstant;
import com.tbit.uqbike.object.pojo.*;
import com.tbit.uqbike.object.pojo.dto.UserAuthLogDTO;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.common.entity.view.PageResult;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.UserAuthLogService;
import com.tbit.uqbike.webmanager.dao.core.BrandDiscountConfigDao;
import com.tbit.uqbike.webmanager.dao.core.UserDao;
import com.tbit.uqbike.webmanager.dao.core.UserDiscountDao;
import com.tbit.uqbike.webmanager.dao.core.UsermsgDao;
import com.tbit.uqbike.webmanager.dao.log.UserAuthLogDao;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:BUGTian
 * @DATE: 2022/9/23
 */
@Service
public class UserAuthLogServiceImpl extends ServiceImpl<UserAuthLogDao, UserAuthLog> implements UserAuthLogService {

    @Autowired
    private UserAuthLogDao userAuthLogDao;

    @Autowired
    private BrandDiscountConfigDao brandDiscountConfigDao;

    @Autowired
    private UserDiscountDao userDiscountDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UsermsgDao usermsgDao;

    @Override
    public Result<PageResult<UserAuthLog>> queryPage(Integer page, Integer size, Integer accountId, Integer adAccountId, String userName, String phone, Integer configId, Integer state, Date startTime, Date endTime) {
        Assert.notNulls("分页参数不能为空", page, size);
        PageInfo<UserAuthLog> pageInfo = PageHelper.startPage(page, size).doSelectPageInfo(() -> userAuthLogDao.queryPage(accountId, adAccountId, userName, phone, configId, state, startTime, endTime));
        List<UserAuthLog> list = pageInfo.getList();
        List<BrandDiscountConfig> brandDiscountConfigs = brandDiscountConfigDao.getAll();
        Map<Integer, String> nameMap = new HashMap<>();
        for (BrandDiscountConfig brandDiscountConfig : brandDiscountConfigs) {
            nameMap.put(brandDiscountConfig.getConfigId(), brandDiscountConfig.getName());
        }
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(a -> a.initTypeName(nameMap));
        }
        return Result.success(new PageResult<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), list));
    }

    @Override
    public Result audit(LoginInfo login, UserAuthLogDTO userAuthLogDTO) {
        Assert.notNulls("参数有误", userAuthLogDTO.getUserAuthLogId(), userAuthLogDTO.getState());
        UserAuthLog logInDb = getById(userAuthLogDTO.getUserAuthLogId());
        if (logInDb == null) {
            return Result.error("审核信息不存在");
        }
        if (UserAuthLogConstant.AUDIT_FAIL.equals(logInDb.getState()) || UserAuthLogConstant.AUDIT_SUCCESS.equals(logInDb.getState())) {
            return Result.error("已审核过的信息不允许修改");
        }
        Date handleTime = new Date();
        logInDb.setHandleTime(handleTime)
                .setHandleUserId(login.getAccountUserId())
                .setMsg(userAuthLogDTO.getMsg())
                .setState(userAuthLogDTO.getState());
        updateById(logInDb);
        User user = userDao.getByUserId(logInDb.getUserId());
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (StringUtils.isEmpty(user.getIdNO())) {
            return Result.error("用户尚未实名认证");
        }
        //发送消息
        Usermsg usermsg = new Usermsg();
        usermsg.setMsgstate(0)
                .setUserid(user.getUserId())
                .setCreatetime(handleTime)
                .setMsgtype(0)
                .setTitle("特殊人群认证审核结果");
        if (UserAuthLogConstant.AUDIT_SUCCESS.equals(logInDb.getState())) {
            userDiscountDao.insert(new UserDiscount(logInDb.getUserId(), user.getAccountId(), user.getIdNO(), new Date(), logInDb.getType(), logInDb.getMsg()));
            usermsg.setContent("您申请的特殊人群认证审核通过!");
            usermsgDao.insert(usermsg);
        }
        if (UserAuthLogConstant.AUDIT_FAIL.equals(logInDb.getState())) {
            usermsg.setContent("您申请的特殊人群认证审核不通过，请前往用户设置查看！");
            usermsgDao.insert(usermsg);
        }
        return Result.success();
    }

    @Override
    public Result cleanUserAuth(Integer userId) {
        User user = userDao.getByUserId(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        //删除折扣记录
        userDiscountDao.deleteByMap(map);
        //删除审核记录
        userAuthLogDao.deleteByMap(map);
        if (StringUtils.isNotEmpty(user.getIdNO())) {
            //根据身份证号和品牌id删除折扣记录
            map.clear();
            map.put("idNO", user.getIdNO());
            map.put("accountId", user.getAccountId());
            userDiscountDao.deleteByMap(map);
            //删除关联的身份证用户提交的审核申请
            map.put("idNo", user.getIdNO());
            List<User> userList = userDao.getByAccountIdAndIdNo(map);
            if (!userList.isEmpty()) {
                userAuthLogDao.delete(new QueryWrapper<UserAuthLog>().in("userId", userList.stream().map(User::getUserId).collect(Collectors.toList())));
            }
        }
        return Result.success();
    }

    @Override
    public UserAuthLog selectByUserId(Integer userId) {
        return userAuthLogDao.selectByUserId(userId);
    }
}
